import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutterApp/api/Api.dart';
import 'package:flutterApp/provider.dart/Devices.dart';
import 'package:provider/provider.dart';
import '../common//Button.dart';
import '../common//Utils.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _list = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Future.delayed(Duration.zero).then(){
    //   String count = Provider.of<Devices>(context).count;
    //   print("=====");
    //   print(count);
    // };
    Future.delayed(Duration.zero).then((_) {
      String count = Provider.of<Devices>(context, listen: false).count;
      if (count == "1") {
        this.getData();
      }
    });
  }

  bool _isHasDevices = false;
  void addDevicesFun() async {
    Navigator.pushNamed(context, '/selectDevicesType');
  }

  void getData() async {
    //showOkAlertDialog(context:context,title:"登录成功");
    Response response = await getDevices();
    Map<String, dynamic> data = response.data;
    if (data['isCorrect']) {
      setState(() {
        _list = data['data']['data']['deviceArray'];
        _list.add({
          "alarmStatus": "正常",
          "deviceTypeName": "燃气阀门",
        });
        _list.add({
          "alarmStatus": "正常",
          "deviceTypeName": "",
        });
      });
    }
  }

  //返回没有设备的布局
  Widget _noneDevices() {
    return Container(
      decoration: new BoxDecoration(
        color: Colors.white,
      ),
      child: Column(children: <Widget>[
        Image.asset('images/banner-index.png'),
        Container(
            alignment: Alignment(0, 0),
            padding: EdgeInsets.fromLTRB(30, 80, 30, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Image.asset('images/icon-none.png', width: 80),
                SizedBox(
                  height: 20,
                ),
                Text("你当前还未添加设备"),
                SizedBox(
                  height: 80,
                ),
                Button(name: '添加设备', callback: this.addDevicesFun)
              ],
            ))
      ]),
    );
  }

  List<Widget> _getListData() {
    var tempList = _list.map((item) {
      return InkWell(
          onTap: () {
            print(item['deviceTypeName']);
            if (item['deviceTypeName'] == "") return;
            if (isAlarm(item['deviceTypeName'])) {
              Navigator.pushNamed(context, '/AlarmPage');
            } else {
              Navigator.pushNamed(context, '/ValvePage');
            }
          },
          child: Container(
            alignment: Alignment.center,
            height: 400.0,
            padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
            child: item['deviceTypeName'] != ""
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                          isAlarm(item['deviceTypeName'])
                              ? 'images/rqbjq1-1.png'
                              : 'images/rqbjq1-1-0-device.png',
                          width: 50),
                      SizedBox(height: 10),
                      Text(
                        item['deviceTypeName'],
                        textAlign: TextAlign.center,
                        //style: TextStyle(fontSize: 20),
                      ),
                      SizedBox(height: 10),
                      Text(
                        '状态：' + item['alarmStatus'],
                        textAlign: TextAlign.center,
                        style: TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                      SizedBox(height: 10),
                      isAlarm(item['deviceTypeName'])
                          ? Text(
                              "剩余时间: 0:45Min",
                              style: TextStyle(color: Colors.blue),
                            )
                          : Image.asset('images/switch-0.png', width: 30),
                    ],
                  )
                : Image.asset('images/icon-plus.png', width: 70),
            decoration: BoxDecoration(
                color: Colors.white,
                //  boxShadow: [ BoxShadow(
                //   color: Colors.grey[200],
                //   offset: Offset(0.0, 1.0), //阴影y轴偏移量
                //    blurRadius: 2,
                //   )],
                border: Border.all(
                    color: Color.fromRGBO(233, 233, 233, 0.9), width: 1)),
          ));
    });
    // ('xxx','xxx')
    var result = tempList.toList();
    return result;
  }

  //返回有设备的布局
  Widget _hasDevices() {
    //  this.getData();
    var size = MediaQuery.of(context).size;

    /*24 is for notification bar on Android*/
    final double itemHeight = (size.height - kToolbarHeight - 250) / 2;
    final double itemWidth = size.width / 2;
    return Container(
      child: Column(children: <Widget>[
        Image.asset('images/banner-index.png'),
        Container(
            padding: EdgeInsets.fromLTRB(10, 20, 10, 0),
            child: GridView.count(
                shrinkWrap: true,
                controller: ScrollController(keepScrollOffset: false),
                physics: ScrollPhysics(),
                // childAspectRatio: 2 / 2.5,
                childAspectRatio: (itemWidth / itemHeight),
                crossAxisSpacing: 8.0, //水平子 Widget 之间间距
                mainAxisSpacing: 8.0, //垂直子 Widget 之间间距
                padding: EdgeInsets.all(10),
                crossAxisCount: 2, //一行的 Widget 数量
                children: this._getListData()))
      ]),
    );
  }

  Widget _createPage() {
    return Container(
        decoration: new BoxDecoration(
            color: this._isHasDevices ? Colors.grey[100] : Colors.white),
        height: double.infinity,
        child: SingleChildScrollView(
          child: this._isHasDevices ? this._hasDevices() : this._noneDevices(),
        ));
  }

  @override
  Widget build(BuildContext context) {
    String count = Provider.of<Devices>(context).count;
    if (count == "1") {
      this._isHasDevices = true;
    } else {
      this._isHasDevices = false;
    }
    return Container(
        child: Scaffold(
            appBar: AppBar(
              title: Text("我的厨房"),
              centerTitle: true,
              // backgroundColor:Color(0xFF000000)
            ),
            bottomNavigationBar: BottomNavigationBar(
              selectedItemColor: Colors.blue,
              onTap: (int index) {
                if (index == 1) {
                  //路由跳转
                  Navigator.pushNamed(context, '/catch');
                } else if (index == 2) {
                  Navigator.pushNamed(context, '/services');
                }
              },
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.home), title: Text("我的厨房")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.category), title: Text("异常报警")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.settings), title: Text("服务大厅"))
              ],
            ),
            body: this._createPage()));
  }
}
